import {Component, OnInit} from '@angular/core';
import {ApiService} from "@core/services/http/api.service";
import { ApesMessageService } from '@shared/apes/message';
import {UserAuthService} from "@core/services/user-auth.service";

@Component({
  selector: 'app-dashboard-v1',
  templateUrl: './v1.component.html',
})
export class DashboardV1Component implements OnInit {

  // 图表相关操作
  topSalesData: any[] = [];
  lastSalesData: any[] = [];

  targetAmount: any = 0.00;
  actualAmount: any = 0.00;

  /**用户信息**/
  user: any;

  constructor(private apiService: ApiService, public msg: ApesMessageService,  private userService: UserAuthService,) {
    this.userService.getUser().subscribe(user => this.user = user);
  }

  ngOnInit() {
    this.getChartData();
    this.getProgressData();
  }

  getChartData() {
    let data = { 'interfaceMethod': 'ipmVipService.queryMDRank', 'pdata': { 'GSID': this.user.post.company.id } };
    this.apiService.post('report.interface', {'body': JSON.stringify(data)})
      .subscribe(
      resultData => {
        if (!resultData) return;

        resultData = JSON.parse(resultData);
        if (resultData.success) {
          const array = JSON.parse(resultData.obj);
          let topRankList = array.slice(0, 10);
          let lastRankList = array.slice(array.length - 10, array.length).reverse();
          topRankList = topRankList.sort(this.sortarr('FWXSJE'));
          lastRankList = lastRankList.sort(this.sortarr('FWXSJE'));
          this.topSalesData = topRankList.map((value) => {
            return {x: value['MDMC'], y: value['FWXSJE']};
          });
          this.lastSalesData = lastRankList.map((value) => {
            return {x: value['MDMC'], y: value['FWXSJE']};
          });
        } else {
          this.msg.info(resultData.msg);
        }
      });
  }

  getProgressData() {
    let data = { 'interfaceMethod': 'ipmVipService.queryMDAllMoney', 'pdata': { 'GSID': this.user.post.company.id } };
    this.apiService.post('report.interface', {'body': JSON.stringify(data)})
      .subscribe(
      resultData => {
        if (!resultData) return;

        resultData = JSON.parse(resultData);
        if (resultData.success) {
          const amountData = JSON.parse(resultData.obj);
          this.targetAmount = (Number(amountData.MDXSMB)).toFixed(2);
          this.actualAmount = (Number(amountData.ALLMONEY) / 10000).toFixed(2);

        } else {
          this.msg.info(resultData.msg);
        }
      });
  }

  progress = [{
    title: '月销售任务',
    total: '截止昨日已完成 :',
    rateLeft: '本月销售目标额 :',
    rateRight: '距完成目标还差 :',
  }];


  // 排序 倒序
  sortarr(key) {
    return function (a, b) {
      a[key] == undefined ? a[key] = 0 :
        b[key] == undefined ? b[key] = 0 : 0 ;
      return a[key] - b[key];
    };
  }

}
